package com.ysstech.valuation.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.util.BigDecimalUtil;
import com.ysstech.common.util.DateUtil;
import com.ysstech.valuation.entity.BondFaceMoneyInfo;
import com.ysstech.valuation.entity.BondInfo;
import com.ysstech.valuation.mapper.BondInfoMapper;
import com.ysstech.valuation.service.BondFaceMoneyInfoService;
import com.ysstech.valuation.service.BondInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 债券信息表 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2021-08-11
 */
@Service
public class BondInfoServiceImpl extends ServiceImpl<BondInfoMapper, BondInfo> implements BondInfoService {

    @Autowired
    private BondFaceMoneyInfoService bondFaceMoneyInfoService;

    /**
     * 查询债券基础信息列表
     *
     * @param bondInfo
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<BondInfo> queryAllBondInfo(BondInfo bondInfo, PageBean pageBean) throws Exception {
        QueryWrapper<BondInfo> wrapper = this.getQueryWrapper(bondInfo);
        IPage pageBalance = this.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), wrapper);
        this.switchedListBondInfo(pageBalance.getRecords());
        return new PageBean<>(pageBalance);
    }

    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    public List<BondInfo> switchedListBondInfo(List<BondInfo> list) throws Exception {
        for (BondInfo bondInfo : list) {
            if (null == bondInfo) {
                continue;
            }
        }
        return list;
    }

    /**
     * 查询条件
     *
     * @param bondInfo
     * @return
     * @throws Exception
     */
    private QueryWrapper<BondInfo> getQueryWrapper(BondInfo bondInfo) throws Exception {
        QueryWrapper<BondInfo> wrapper = new QueryWrapper<>();
        if (null == bondInfo) {
            return wrapper;
        }
        if (StringUtils.isNotBlank(bondInfo.getSecurityName())) {
            wrapper.like("SECURITY_NAME", bondInfo.getSecurityName());
        }
        return wrapper;
    }


    /**
     * 票面利率（税前或者税后）/年计息天数（365或者366）*已计息天数*票面金额/100
     * 获取百元利息
     */
    public BondInfo getBillRates(BondInfo bondInfo, String fdate) throws Exception {
        try {
            if (null == bondInfo || StringUtils.isBlank(fdate) || StringUtils.isBlank(bondInfo.getSecurityCode())) {
                return null;
            }
            BigDecimal price = new BigDecimal("100");
            BondFaceMoneyInfo bondFaceMoneyInfo = new BondFaceMoneyInfo();
            bondFaceMoneyInfo.setStartAdjustRateDate(DateUtil.strToLocalDate(fdate));
            bondFaceMoneyInfo.setSecurityCode(bondInfo.getSecurityCode());
            BondFaceMoneyInfo mapPrice = bondFaceMoneyInfoService.queryBondFaceMoneyInfoCache(bondFaceMoneyInfo);
            String startBearingData = DateUtil.localDateToStr(bondInfo.getStartBearingData());
            if (null != mapPrice && null != mapPrice.getFaceMoney()) {
                price = mapPrice.getFaceMoney();
                startBearingData = DateUtil.localDateToStr(mapPrice.getStartAdjustRateDate()); //计息起始日
            }
            /**
             *  这个计息区间的开始时间和结束时间
             *  根据业务时间计算已计息天数
             */

            int i = 1;
            String startBearingDataTemp = startBearingData;
            while (DateUtil.differentDaysByString(fdate, DateUtil.addYear(startBearingData, i)) < 0) {
                startBearingDataTemp = DateUtil.addYear(startBearingData, i);
                i++;
            }
            String qjjzr = DateUtil.addYear(startBearingDataTemp, 1);
            //已计息天数
            int alreadyBearingData = DateUtil.differentDaysByString(startBearingDataTemp, fdate) + 1;
            //实际计息年天数
            int realBearingData = DateUtil.differentDaysByString(startBearingDataTemp, qjjzr);
            BigDecimal perTaxFaceRate = BigDecimalUtil.divide(bondInfo.getPerTaxFaceRate().multiply(new BigDecimal(alreadyBearingData)).multiply(price),
                    new BigDecimal(realBearingData).multiply(new BigDecimal("100")), 8);
            bondInfo.setPerTaxFaceRate(perTaxFaceRate);
            BigDecimal faceRate = BigDecimalUtil.divide(bondInfo.getFaceRate().multiply(new BigDecimal(alreadyBearingData)).multiply(price),
                    new BigDecimal(realBearingData).multiply(new BigDecimal("100")), 8);
            bondInfo.setFaceRate(faceRate);
        } catch (Exception ex) {
            log.error("计算债券百元利息失败" + ex.toString());
            throw new Exception(ex);
        }
        return bondInfo;
    }





}
